const SOCKET_PORT = 6600;
const RESPONSE_DELAY = 5000;
const THROW_RESPONSE_DELAY = 10000;
var loginTimer;

var Socket = {
  socket: null,
  
  connect: function() {
    if (this.socket)
      this.disconnect();
    var socketServer = 'http://' + location.hostname + ':' + SOCKET_PORT;
    this.socket = io.connect(socketServer, {
      'max reconnection attempts': 5
      //'reconnection limit': 4,
      //'connect timeout': 2000
    });
    this.registerSocketEvent();
    this.login();
  },

  disconnect: function() {
    this.socket.disconnect();
    this.socket = null;
  },

  login: function() {
    this.socket.emit('login', 'login', function() {
      // The first web socket connection succeed.
      clearTimeout(loginTimer);
    });
    
    loginTimer = setTimeout(function() {
      // Send login request failed.
      // TODO: Show error message and retry button
    }, RESPONSE_DELAY);

//    setInterval(function() {
//      Socket.throwDice(2);
//    }, 3000);
  },

  registerSocketEvent: function() {
    var that = this;
    var socket = this.socket;

    socket.on('login_result', function(data) {
      Client.handleLogin(data);
    });

    socket.on('game_start', function() {
      Client.startGame();
    });

    socket.on('throw_request', function() {
      Client.handleThrowRequest();
    });

    socket.on('game_end', function(data) {
      var result = data.winner == Client.playerRole;
      Client.endGame(result);
    });

    socket.on('disconnect_view', function() {
      Client.handleViewDisconnection();
    });

    socket.on('view_not_ready', function() {
      Client.handleViewNotReady();
    });

    socket.on('connect', function() {
      Message.setMainInfo('恢复！');
    });

    socket.on('disconnect', function() {
      Message.setMainInfo(Message.get('lostConnection'));
      Client.hidePlayerRole();
      Client.showReloadButton(Message.get('retry'));
    });

    socket.on('reconnect_failed', function() {
      Message.setMainInfo('reconnect_failed');
      console.log('reconnect_failed');
    });

    socket.on('close', function() {
      console.log('server closed!!');
    });
  },

  throwDice: function(result) {
    Socket.socket.emit('throw_response', result, function() {
    });
  }
};